﻿using System;
using System.Linq;

namespace Components
{
    public partial class SearchBox : System.Web.UI.UserControl
    {
        public SearchScope SearchScope { get; set; }

        public string Keyword { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                AddCssLink();
                if (SearchScope == SearchScope.Shop)
                    searchScopeRadioButtons.Items[0].Selected = true;
                else
                    searchScopeRadioButtons.Items[1].Selected = true;

                keywordTextBox.Text = Keyword;
            }
        }

        private void AddCssLink()
        {
            var controls = Page.Header.Controls.OfType<System.Web.UI.HtmlControls.HtmlLink>().ToArray();

            string href = ResolveUrl("~/Styles/SearchBox.css");
            for (int i = 0; i < controls.Length; i++)
            {
                if (controls[i].Href == href)
                    return;
            }

            var link = new System.Web.UI.HtmlControls.HtmlLink { Href = href };
            link.Attributes.Add("rel", "stylesheet");
            link.Attributes.Add("type", "text/css");
            Page.Header.Controls.Add(link);
        }

        protected void searchButton_Click(object sender, EventArgs e)
        {
            if (searchScopeRadioButtons.SelectedItem.Text == "Shop")
            {
                Response.Redirect("ShopSearchResult.aspx?q=" + Server.UrlEncode(keywordTextBox.Text));
            }
            else
                Response.Redirect("ProductSearchResult.aspx?q=" + Server.UrlEncode(keywordTextBox.Text));
        }
    }
    public enum SearchScope
    {
        Shop,
        Product
    }
}